package com.qf.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 硬件设备网关
 * 所有硬件设备认证都要经过这里, 如果是登录路径无条件放行, 其他路径返回401权限不足异常
 * @author 千锋健哥
 */
@Component
public class MqttAuthFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2. 获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取用户访问的uri路径
        String path = request.getURI().getPath();

        //4. 判断如果uri路径是硬件设备登录路径无条件放行
        if (path.contains("/driver/auth/login")) {
            return chain.filter(exchange);
        }

        //5. 其他情况返回401无权限
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
